package acs.offer.server;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.controller.EventBus;
import acs.offer.pojo.Message;
import acs.offer.pojo.RequestEnum;
import acs.offer.pojo.TranstractDate;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ServerHandler extends SimpleChannelInboundHandler<Message> {
    private static Map<String,Channel> channelMap=new HashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        System.out.println("收到客户端数据");
        System.out.println(msg);
        Params params = Params.build();
//        params.put("request",JSON.parseObject(msg.getContent(),TranstractDate.class));
		TranstractDate transtract = JSON.parseObject(msg.getContent(), TranstractDate.class);
		RequestEnum requestEnum = transtract.getRequestEnum();
        params.put(Constant.MESSAGE,msg);
        params.put(Constant.SESSION_ID,msg.getHeader().getSessionId());
        params.put(Constant.REQUEST_ENUM,requestEnum);
        EventBus.getInstance().putMessage(EventType.CLICK_REQUEST,params);
        channelMap.put(msg.getHeader().getSessionId(), ctx.channel());
    }

    public static void sendMessage(Message message) {
    	Channel channel = channelMap.remove(message.getHeader().getSessionId());
    	if(channel==null) {
    		throw new RuntimeException("服务端找不到对应客户端的channel");
    	}
    	channel.writeAndFlush(message);
//        channelGroup.forEach(ch->{
//            ch.writeAndFlush(Message.build(s));
//        });
    }

    //有新连接加入
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//        Channel channel = ctx.channel();
//        channelGroup.add(channel);
    }
}
